'use strict';
'require view';
'require ui';
'require form';
'require rpc';
'require tools.widgets as widgets';

var formData = {
};
var callServiceList = rpc.declare({
	object: 'service',
	method: 'list',
	params: ['name'],
	expect: {
		'': {}
	}
});
/**Entry Setting */

var callGetLoraAddr = rpc.declare({
    object: 'sihan.energy',
    method: 'query_addr',
    params: [],
    expect: {}
});

var callSetLoraTransAddr = rpc.declare({
    object: 'sihan.energy',
    method: 'set_trans',
    params: ['mode','addr','type'],
    expect: {}
});
var callGetLoraTrans = rpc.declare({
    object: 'sihan.energy',
    method: 'query_trans',
    params: [],
    expect: {}
});
var callSetSleepTime = rpc.declare({
    object: 'sihan.energy',
    method: 'set_sleep',
    params: ['hours','minutes','seconds'],
    expect: {}
});
var callGetEntryInfo = rpc.declare({
    object: 'sihan.energy',
    method: 'query_timeinfo',
    params: [],
    expect: {}
});
var callSetWorkTime = rpc.declare({
    object: 'sihan.energy',
    method: 'set_work',
    params: ['hours','minutes','seconds'],
    expect: {}
});
/******************************************/
var bridgeConf = [
	[form.ListValue, 'type', _('网桥类型'), _(''),{
		values: [[1,'小号网桥'], [2,'大号网桥']]
	}],
	[form.Value, 'ip', _('网桥IP'), _('网桥IP.'), {
		datatype: 'ipaddr'
	}],
];
var energyConf = [
	[form.Value, 'device_sn', _('设备编号'), _('管理设备编号.')],
	[form.Value, 'energy_sn', _('电源编号'), _('16进制编码.')],
];

var serverConf = [
    [form.Flag, 'enable', _('是否启用'), _('勾选后服务器启用.'), {
		datatype: 'bool'
	}],
	[form.Value, 'host', _('MQTT地址'), _('服务器IP.'), {
		datatype: 'ipaddr'
	}],
    [form.Value, 'port', _('MQTT端口'), _('服务器端口.'), {
		datatype: 'port'
	}],
    [form.Value, 'username', _('用户名'), _('MQTT用户名.')],
	[form.Value, 'password', _('密码'), _('MQTT密码'), {
		password: true
	}],
    [form.Value, 'subtopic', _('接收数据主题'), _('设备接收数据主题')],
    [form.Value, 'pubtopic', _('发送数据主题'), _('设备发送数据主题')],
];
function setParams(o, params) {
	if (!params) return;
	for (var key in params) {
		var val = params[key];
		if (key === 'values') {
			for (var j = 0; j < val.length; j++) {
				var args = val[j];
				if (!Array.isArray(args))
					args = [args];
				o.value.apply(o, args);
			}
		} else if (key === 'depends') {
			if (!Array.isArray(val))
				val = [val];
			for (var j = 0; j < val.length; j++) {
				var args = val[j];
				if (!Array.isArray(args))
					args = [args];
				o.depends.apply(o, args);
			}
		} else {
			o[key] = params[key];
		}
	}
	if (params['datatype'] === 'bool') {
		o.enabled = 'true';
		o.disabled = 'false';
	}
}
function defTabOpts(s, t, opts, params) {
	for (var i = 0; i < opts.length; i++) {
		var opt = opts[i];
		var o = s.taboption(t, opt[0], opt[1], opt[2], opt[3]);
		setParams(o, opt[4]);
		setParams(o, params);
	}
}

function getServiceStatus() {
	return L.resolveDefault(callServiceList('idc_service'), {})
		.then(function(res) {
			var isRunning = false;
			try {
				isRunning = res['idc_service']['instances']['instance1']['running'];
			} catch (e) {}
			return isRunning;
		});
}
function renderStatus(isRunning) {
	var renderHTML = "";
	var spanTemp = '<em><span style="color:%s"><strong>%s %s</strong></span></em>';
	if (isRunning) {
		renderHTML += String.format(spanTemp, 'green', _("IDC Service"), _("RUNNING"));
	} else {
		renderHTML += String.format(spanTemp, 'red', _("IDC Service"), _("NOT RUNNING"));
	}
	return renderHTML;
}

return view.extend({
    load: function() {
        return Promise.all([callGetEntryInfo(),callGetLoraTrans(),callGetLoraAddr()]);;
    },
	openCannel: function(param){
	},
    render:function(data){
		console.log("data:", data);
        var m,s,o,pass, test_btn;
		//m = new form.JSONMap(formData, _('Router Password'), _('Changes the administrator password for accessing the device'));
        m=new form.Map('idc_app','边带设备配置');
		/**
        s = m.section(form.NamedSection, '_status');
		s.anonymous = true;
		s.render = function(section_id) {
			L.Poll.add(function() {
				return L.resolveDefault(getServiceStatus())
					.then(function(res) {
						var view = document.getElementById("service_status");
						view.innerHTML = renderStatus(res);
					});
			});
			return E('div', {
				class: 'cbi-map'
			}, E('fieldset', {
				class: 'cbi-section'
			}, [E('p', {
				id: 'service_status'
			}, _('Collecting data ...'))]));
		}
		*/
        s = m.section(form.NamedSection, 'common', 'conf');
        s.anonymous = true;
        s.addremove = false;
        s.tab("general",  _("通用配置")) ;
        //两个参数，分别是rip和rport
		s.taboption("general", form.Flag, "iot_enable", "是否采集边带信息:", "");
		s.taboption("general", form.Flag, "bridge_enable", "是否采集网桥信息:", "");
		s.taboption("general", form.Flag, "lte_enable", "是否采集4G信息:", "");
		s.taboption("general", form.Flag, "mesh_enable", "是否采集Mesh信息:", "");

        return m.render();
    },
    // handleSaveApply: null,
//    handleSave: null,
//    handleReset: null
});